package com.powernode.common.aop;

import com.powernode.common.constant.RedisConstant;
import com.powernode.common.execption.PowerException;
import com.powernode.common.result.ResultCodeEnum;
import com.powernode.common.util.AuthContextHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.Objects;

/**
 * <p>切面类</p>
 * <p>1. 处理用户id</p>
 * <p>2. 从request中获取用户id</p>
 * <p>3. 根据token从redis中获取用户id</p>
 * <p>4. 将用户id设置到ThreadLocal中，AuthContextHolder</p>
 */
@Aspect
@Component
public class PowerLoginAspect {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Before("execution(* com.powernode.*.controller.*.*(..)) " +
            "&& @annotation(com.powernode.common.annotation.PowerLogin)")
    public void before() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(servletRequestAttributes).getRequest();
        String token = request.getHeader("token");
        System.out.println("调试信息");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            System.out.println(headerName + ":" + headerValue);
        }
        if (!StringUtils.hasText(token))
            throw new PowerException(ResultCodeEnum.LOGIN_AUTH);
        String userId = (String) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        AuthContextHolder.setUserId(Long.valueOf(Objects.requireNonNull(userId)));
    }
}